<template>
  <div class="emerEqptManager">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.eqpt_delete" @click="handleDelete">删 除</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" plain v-if="permission.eqpt_import" @click="handleImport">导入</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.eqpt_export" @click="handleExport">导出</el-button>
        </template>

        <!-- 应对事故类型表格自定义 -->
        <template slot="ydsglx" slot-scope="scope">
          <div>{{cellChemicals(scope.row)}}</div>
        </template>

        <!-- 最近保养时间表格自定义 -->
        <template slot="zjbysj" slot-scope="scope">
          <div>{{xcbysjIsNull(scope.row)}}</div>
        </template>

        <!--地图表单自定义-->
        <template slot="mapForm">
          <div v-if="showMap">
            <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
              <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
                <template slot="append">
                  <el-button icon="el-icon-search" id="citySearch"></el-button>
                </template>
              </el-input>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
            </baidu-map>
          </div>
        </template>

        <!--维保操作-->
        <template slot-scope="scope" slot="wbcz">
          <el-form label-width="0px">
            <td style="border: 0px">
              <el-button type="success" size="small" @click="opentjwbjl(scope.row)">添加维保记录</el-button>
            </td>
            <td style="border: 0px">
              <el-button type="primary" size="small" @click="openwbjjl(scope.row)">查看维保记录</el-button>
            </td>
          </el-form>
        </template>

      </avue-crud>

      <!-- 维保记录弹窗-->
      <el-dialog title="添加维保记录" :visible.sync="tjwbjlBox" append-to-body @close='closeDialogMaintion' width="1200px">
        <avue-form ref="form" v-model="mobj" :option="maintainoption">
        </avue-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeDialogMaintion">取 消</el-button>
            <el-button type="primary" @click="saveMaintain">确 定</el-button>
          </span>
      </el-dialog>

      <!-- 维保历史弹窗-->
      <el-dialog title="查看维保历史" :visible.sync="wbjlBox" append-to-body   width="1200px">
        <maintain :eqptId="eqptId"
        :eqptbysj="eqptbysj"
        :wbjlBox="wbjlBox">
        </maintain>
      </el-dialog>

      <!--导入弹窗-->
      <el-dialog title="应急装备据导入"
                 append-to-body
                 :visible.sync="excelBox"
                 width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false"
                   :upload-before="beforeUpload"
                   :upload-after="uploadAfter"
                   :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove,getydsglx} from "@/api/emer/eqpt";
  import {validateTelephone,validateDigit} from "@/api/mmhi/validate";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import maintain from '@/views/emer/maintain.vue';
  import {msave} from "@/api/emer/maintain";
  import {getToken} from "@/util/auth";
  import {mapGetters} from "vuex";

  export default {
    components:{
      maintain
    },
    data() {
      var validateDigit1 = (rule, value, callback) => {
        let dig=/^[0-9]*$/;
        if(value!="") {
          if(!dig.test(value)){
            callback(new Error('只能输入数字！'))
          }else{
            callback()
          }
        }else{
          if(rule.required == true){
            callback(new Error('请输入'+this.findObject(this.option.column, rule.field).label))
          } else {
            callback()
          }
        }
      }
      return {
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/emerEqpt/import"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        },
        eqptId:"",
        eqptbysj: "",
        maintainoption:{
          emptyBtn:false,
          submitBtn:false,
          column: [
            {
              label: "保养人",
              prop: "byr",
              align: "center",
              rules: [{
                required: true,
                message: "请输入保养内容",
                trigger: "blur"
              }]
            },
            {
              label: "保养周期",
              prop: "byzq",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_byzq",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入保养内容",
                trigger: "blur"
              }]
            },
            {
              label: "保养内容",
              prop: "bynr",
              align: "center",
              rules: [{
                required: false,
                message: "请输入保养内容",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
          ]
        },

        wbjlBox:false,
        mobj:{},

        tjwbjlBox:false,

        cellChemicalsList: {},
        //地图设置
        mapPosition: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        center: {
          lng: 121.4472540000,
          lat: 31.3236200000
        },
        zoom: 10,
        dragging: false,
        showMap: true,
        searchWord: "",
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "装备分类",
              prop: "zbfl",
              align: "center",
              type:"select",
              width:100,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_eqpt",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入装备分类",
                trigger: "blur"
              }]
            },
            {
              label: "装备名称",
              prop: "zbmc",
              align: "center",
              maxlength:100,
              search:true,
              rules: [{
                required: true,
                message: "请输入装备名称",
                trigger: "blur"
              }]
            },
            {
              label: "规格型号",
              prop: "ggxh",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入规格型号",
                trigger: "blur"
              }]
            },
            {
              label: "数量",
              prop: "sl",
              align: "center",
              maxlength:11,
              rules: [{
                required: true,
                validator:validateDigit1,
                trigger: "blur"
              }]
            },
            {
              label: "功能用途",
              prop: "gnyt",
              align: "center",
              maxlength:250,
              rules: [{
                required: true,
                message: "请输入功能用途",
                trigger: "blur"
              }]
            },
            {
              label: "自储数量",
              prop: "zcsl",
              align: "center",
              maxlength:11,
              rules: [{
                required: true,
                validator:validateDigit1,
                trigger: "blur"
              }]
            },
            {
              label: "代储数量",
              prop: "dcsl",
              align: "center",
              maxlength:11,
              rules: [{
                required: true,
                validator:validateDigit1,
                trigger: "blur"
              }]
            },
            {
              label: "储存单位",
              prop: "ccdw",
              align: "center",
              maxlength:10,
              rules: [{
                required: true,
                message: "请输入储存单位",
                trigger: "blur"
              }]
            },
            {
              label: "地址",
              prop: "dz",
              align: "center",
              maxlength:1000,
              span:24,
              rules: [{
                required: true,
                message: "请输入地址",
                trigger: "blur"
              }]
            },
            {
              label: "绑定区域",
              prop: "bdqy",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入绑定区域",
                trigger: "blur"
              }]
            },
            {
              label: "保管部门",
              prop: "bgbm",
              align: "center",
              width:100,
              type:"tree",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入保管部门",
                trigger: "blur"
              }]
            },
            {
              label: '',
              align: "center",
              prop: 'map',
              span: 24,
              hide: true,
              formslot: true,
            },
            {
              label: "经度",
              prop: "jd",
              align: "center",
              width:90,
              maxlength:10,
              rules: [{
                required: true,
                message: "请输入经度",
                trigger: "blur"
              }]
            },
            {
              label: "纬度",
              prop: "wd",
              align: "center",
              width:90,
              maxlength:10,
              rules: [{
                required: true,
                message: "请输入纬度",
                trigger: "blur"
              }]
            },
            {
              label: "联系人",
              prop: "lxr",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入联系人",
                trigger: "blur"
              }]
            },
            {
              label: "应急电话",
              prop: "yjdh",
              align: "center",
              width:100,
              maxlength:11,
              rules: [{
                required: true,
                validator:validateTelephone,
                trigger: "blur"
              }]
            },
            {
              label: "应对事故类型",
              width:100,
              labelWidth:120,
              prop: "ydsglx",
              align: "center",
              multiple: true,
              slot: true,
              type: "tree",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_eqpt_yjsglx",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入应对事故类型",
                trigger: "blur"
              }]
            },
            {
              label: "最近保养时间",
              width:135,
              prop: "zjbysj",
              align: "center",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "下次保养时间",
              width:135,
              prop: "xcbysj",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              span:24,
              maxlength:1000,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            {
              label: "维保操作",
              prop: "wbcz",
              align: "center",
              width:230,
              viewDisplay: false,
              addDisplay: false,
              editDisplay: false,
              slot: true,
              rules: [{
                required: true,
                message: "请输入备注",
                trigger: "blur"
              }]
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.eqpt_add, false),
          viewBtn: this.vaildData(this.permission.eqpt_view, false),
          delBtn: this.vaildData(this.permission.eqpt_delete, false),
          editBtn: this.vaildData(this.permission.eqpt_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData();
      this.getydsglx();
    },
    methods: {
      //导出摸板
      handleTemplate() {
        window.open(`/api/emerEqpt/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      // 导入前判断
      beforeUpload(file, done, loading) {
        this.uploadFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入成功后1
      uploadAfter1() {
        this.excelBox = false;
        this.$message.success("上传成功");
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      // 导入成功后
      uploadAfter(res, done) {
        done();
        if(this.uploadFailed === true) {
          return;
        }
        this.uploadAfter1()
      },
      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.uploadFailed = true;
      },
      //导出应急装备
      handleExport() {
        this.$confirm("是否导出应急装备数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let qymc = this.query.qymc !== undefined && this.query.qymc !== "" && this.query.qymc !== null ? this.query.qymc : "";
          window.open(`/api/emerEqpt/export?${this.website.tokenHeader}=${getToken()}&qymc=${qymc}`);
        });
      },
      //打开导入弹窗
      handleImport() {
        this.excelBox = true;
      },
      openwbjjl(row){
        this.eqptId=row.id
        this.eqptbysj=row.zjbysj
        this.wbjlBox=true
      },
      saveMaintain(loading){
        this.mobj.businessId=this.eqptId
        this.mobj.type=1
        if (this.mobj.byr == '' || this.mobj.byr==undefined || this.mobj.byzq == ''||this.mobj.byzq==undefined) {
          this.$message.warning("请填写保养人以及保养周期信息");
          loading();
          return;
        }
        msave(this.mobj).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.closeDialogMaintion();
          this.mobj={
            byr:""
          }
        }, error => {
          window.console.log(error);
        });
      },
      closeDialogMaintion() {
        this.mobj={}
        this.tjwbjlBox=false
        this.onLoad(this.page)
      },
      opentjwbjl(row) {
        this.mobj={
          byr:"",
          bynr:"",
          bz:"",
          byzq:""
        }
        this.eqptId=row.id
        this.tjwbjlBox=true
      },
      xcbysjIsNull(row) {
        var zjbysj = row.zjbysj;
        if (zjbysj === undefined || zjbysj === "") {
          return "最近未保养";
        } else {
          return zjbysj
        }
      },
      // 获取应对事故类型列表
      getydsglx() {
        getydsglx().then(res => {
          this.cellChemicalsList = {};
          res.data.data.forEach(item => {
            this.cellChemicalsList[item.dictKey] = item.dictValue;
          });
        })
      },
      // 显示应对事故类型列
      cellChemicals(row) {
        if(row.ydsglx === undefined || typeof row.ydsglx === "object") {
          return "";
        }
        var arr = row.ydsglx.split(",");
        var faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          var fault = this.cellChemicalsList[arr[i]] === undefined ? arr[i] : this.cellChemicalsList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },
      // 地图处理事件
      handler({BMap, map}) {
        let _this = this;
        map.addEventListener('click', function(e) {
          _this.form.jd = e.point.lng
          _this.form.wd = e.point.lat
        });
        _this.$nextTick(() => {
          document.getElementById('citySearch').addEventListener('click', function() {
            let localSearch = new BMap.LocalSearch(map)
            localSearch.setSearchCompleteCallback(searchResult => {
              let poi = searchResult.getPoi(0)
              if(!poi) {
                return _this.$message.warning('该地址不存在')
              } else {
                _this.center = {
                  lng: poi.point.lng,
                  lat: poi.point.lat
                }
                _this.form.jd = poi.point.lng
                _this.form.wd = poi.point.lat
              }
            });
            localSearch.search(_this.searchWord);
          });
        })
      },
      // 初始化数据
      initData() {
        var tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "bgbm");
          column.dicData = res.data.data;
        }).then(() => {

        });
      },
      rowSave(row, done, loading) {
        row.ydsglx = typeof row.ydsglx === "object" ? row.ydsglx.join(",") : row.ydsglx;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    },
    watch:{
      // 表单经度
      'form.jd' (val) {
        if(val) {
          this.mapPosition.lng = val / 1
        }
      },
      // 表单纬度
      'form.wd' (val) {
        if(val) {
          this.mapPosition.lat = val / 1
        }
      },
    }
  };
</script>

<style lang="scss">
  .emerEqptManager {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }

</style>

<style lang="scss" scoped>
  .map {
    width: 100%;
    height: 500px;
  }

</style>
